<?php
/**
 * Created by PhpStorm.
 * User: 图图
 * Date: 2021-6-8
 * Time: 16:29
 */

namespace app\web\controller;

use app\common\model\CommissionLog;
use app\common\model\HandCard;
use app\common\model\HandCard as HandCardM;
use app\common\model\Order;
use app\common\model\ProductOrder;
use app\common\model\Project;
use app\common\service\OrdinaryService;
use app\common\service\ReceiverService;
use app\common\service\VoiceService;
use Carbon\Carbon;
use Exception;
use think\Db;
use app\common\model\Orderproject;
use app\common\model\Duanwei;

/**
 * 前台首页控制器
 * @package app\index\controller
 */
class Index extends Auth
{
    public $noNeedLogin = [];

    public function index()
    {
        $noticeData = Db::name('qt_notic')->where(['status' => 1])->field('id,title')->limit(10)->order('id desc')->select();
        $data['noticeData'] = $noticeData;
        //banner
        $banner = Db::view('qt_banner_position', 'id,name,is_flash,url')
            ->view('qt_banner', 'imgurl,create_time,active_id', 'qt_banner.position_id=qt_banner_position.id', 'left')
            ->where(['qt_banner_position.name_key' => 'index_banner', 'qt_banner.status' => '0'])
            ->order('qt_banner.id', 'desc')
            ->select();
        foreach ($banner as $key => $value) {
            $imgUrl = get_img_path($value['imgurl']);
            $banner[$key]['imgurl'] = $imgUrl;
        }
        $data['banner'] = $banner;
        $this->result('查询成功', $data, 200);
    }


    /**
     * 获取正在使用中的房间列表
     */
    public function room_use()
    {
        if ($this->request->isPost()) {
            $userInfo = $this->userInfo;
            $data = Db::name('qt_room')
                ->field('id,name')
                ->where(['store_id' => $userInfo['store_id']])
                ->whereIn('status_id', ['2', '3', '4', '10'])
                ->order('id asc')
                ->select();
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 房费开始记时
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function room_rate()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if (empty($post['room_id']) || empty($post['type'])) {
                $this->result('缺少参数', '', 204);
            }

            if ($post['type'] == 1) {
                //判断当前房间是否有未结账订单
                $goods_check = Db::name('qt_product_order_item')
                    ->where(['room_id' => $post['room_id'], 'pay_status' => '0'])
                    ->find();
                $order_check = Db::name('qt_order_project')
                    ->where(['room_id' => $post['room_id'], 'pay_status' => '0'])
                    ->find();
                if (empty($goods_check) && empty($order_check)) {
                    $this->result('请先安排服务或下单', '', 204);
                }
                Db::name('qt_room')->where('id', $post['room_id'])->update([
                    'room_cost_start_time' => time(),
                    'is_room_cost' => 2,//修改为结束计时
                ]);
                $this->result('计费开始', '', 200);
            } else {
                Db::name('qt_room')->where('id', $post['room_id'])->update([
                    'room_cost_start_time' => 0,
                    'is_room_cost' => 1,
                    'room_cost_num' => 0,
                ]);
                $this->result('结束计费', '', 200);
            }

        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 购物车列表
     */
    public function list_goods()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['room_id'])) {
                $this->result('缺少房间参数', '', 204);
            }
            $order = Db::name('qt_product_order')->where(['room_id' => $getData['room_id'], 'pay_status' => '0'])->find();
            $data = Db::name('qt_product_order_item')
                ->field('id as order_goods_id,goods_name,goods_total_price,goods_num,create_time,pay_status')
                ->where('order_id', $order['id'])
                ->where(['status' => '1'])
                ->select();
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 删除商品订单
     */
    public function del_goods()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();

            $userInfo = $this->userInfo;
            if (empty($getData['order_goods_id'])) {
                $this->result('缺少订单商品参数', '', 204);
            }
            $find = Db::name('qt_product_order_item')->where('id', $getData['order_goods_id'])->find();
            if ($find['pay_status'] == '1') {
                $this->result('已结账商品禁止删除', '', 204);
            }
            $order_item = Db::name('qt_product_order_item')
                ->alias('oi')
                ->field([
                    'oi.id',
                    'oi.goods_name',
                    'oi.goods_id',
                    'oi.goods_num',
                    'oi.goods_total_price',
                    'oi.hand_card_id',
                    'po.room_id',
                    'po.engineer_id',
                    'r.name as room_name',
                ])
                ->leftJoin('qt_product_order po', 'po.id=oi.order_id')
                ->leftJoin('qt_room r', 'po.room_id=r.id')
                ->where('oi.store_id', $userInfo['store_id'])
                ->where('oi.id', $getData['order_goods_id'])
                ->where(['oi.status' => '1'])
                ->find();

            $text = '房间  ' . $order_item['room_name'] . '  ' . $order_item['goods_name'] . '    数量    ' . $order_item['goods_num'] . ' 退单';
            try {
                Db::startTrans();
                //更新订单详情状态
                Db::name('qt_order_detail')->where('order_goods_id', $getData['order_goods_id'])->update(['status' => '2']);
                //更新商品订单信息
                Db::name('qt_product_order_item')->where('id', $getData['order_goods_id'])->delete();
                //删除提成记录
                Db::name('qt_commission_log')->where(['order_project_id' => $getData['order_goods_id']])->delete();
                //增加库存记录
                $stockModel = new ProductOrder();
                $stockModel::stockInc($order_item['goods_id'], $order_item['goods_num'], $order_item['id'], $this->userInfo);
                //有手牌减掉手牌金额
                if($order_item['hand_card_id'] != null){
                    $handCard = new HandCard();
                    $handCard::decHandCardMoney($order_item,$order_item['hand_card_id'],'2');
                }
                Db::name('qt_send_voice_msg')->insert(['content' => $text, 'type' => 1, 'create_time' => time(), 'voice_type' => 2]);
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('删除失败', '', 204);
            }
            $this->result('删除成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 启用禁用商品
     */
    public function enable()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['goods_id'])) {
                $this->result('缺少商品', '', 204);
            }
            if ($getData['type'] == '1') {
                //启用
                $update = Db::name('qt_goods')
                    ->where('id', $getData['goods_id'])
                    ->update(['status' => '1']);
            } elseif ($getData['type'] == '2') {
                //禁用
                $update = Db::name('qt_goods')
                    ->where('id', $getData['goods_id'])
                    ->update(['status' => '0']);
            }
            if ($update !== false) {
                $this->result('操作成功', '', 200);
            }
            $this->result('更新失败', '', 204);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 上钟
     */
    public function start_project()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['order_id']) || empty($getData['engineer_id'])) {
                $this->result('缺少参数', '', 204);
            }
            if($this->storeInfo['type'] != '1'){
                if(!isset($getData['hand_card_name']) || empty($getData['hand_card_name'])){
                    $this->result('请填写手牌号', '', 204);
                }
            }
            //更新手牌号
            if (isset($getData['hand_card_name']) && !empty($getData['hand_card_name'])) {
                $handCardData = Db::name('qt_hand_card')
                    ->where(['store_id' => $this->userInfo['store_id'], 'name' => $getData['hand_card_name']])
                    ->find();
                if (empty($handCardData)) {
                    $this->result('无效的手牌', '', 204);
                }
                if ($handCardData['status'] != '2') {
                    $this->result('手牌未发放', '', 204);
                }
                //检测停牌
                $checkStatus = HandCard::checkStatus($handCardData['id']);
                if ($checkStatus == false) {
                    $this->result('手牌状态有问题', '', 204);
                }
                //检测最大消费金额
                $money = Db::name('qt_order_project')->where(['id' => $getData['order_id']])->value('price');
                $checkMoney = HandCard::checkMaxMoney($handCardData['id'], $money);
                if ($checkMoney == false) {
                    $this->result('超出手牌最大消费金额', '', 204);
                }
                Db::name('qt_order_project')->where(['id' => $getData['order_id']])->update(['hand_card_id' => $handCardData['id']]);
                //Db::name('qt_order')->where(['id' => $getData['order_id']])->update(['hand_card_id' => $handCardData['id']]);
                //查询总金额
                $money = Db::name('qt_order_project')->where(['id' => $getData['order_id']])->value('price');
                //给手牌加金额
                Db::name('qt_hand_grant')
                    ->where(['hand_card_id' => $handCardData['id']])
                    ->where(['status' => '2'])
                    ->setInc('money', $money);

            }
            //判断提成模式
            $orderProjectData = Db::name('qt_order_project')->where(['id'=>$getData['order_id']])->find();
            if($this->storeInfo['receiver_order_commission_type'] == '3'){
                if($orderProjectData['old_name'] != null || $orderProjectData['old_name'] != ''){
                    //更新提成记录
                    Db::name('qt_commission_log')->where(['type'=>'1','order_project_id'=>$getData['order_id']])->update(['receiver'=>0]);
                    //更新订单提成
                    Db::name('qt_order_project')->where(['id'=>$getData['order_id']])->update(['receiver'=>0]);
                }
            }
            $OrderprojectModel = new Orderproject();
            $res = $OrderprojectModel->start_project($getData['order_id'], $getData['engineer_id'], '1',$this->userInfo);
            if ($res['status']) {
                //上钟成功播报
                $voiceResult = VoiceService::createVoice('上钟成功');
                if ($voiceResult['code'] == 0) {
                    VoiceService::saveVoiceMsg($this->userInfo['store_id'], '上钟成功', $voiceResult['data'], '5', '3', $getData['engineer_id']);
                }
                $this->result('上钟成功', '', 200);
            } else {
                $this->result('上钟失败', $res['msg'], 204);
            }
        } else {
            $this->result('非法请求', '', 204);
        }
    }

    /**
     *下钟操作
     */
    public function end_project()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['order_id']) || empty($getData['engineer_id'])) {
                $this->result('缺少参数', '', 204);
            }
            //判断当前技师是否有其他的未下钟
            $orderProject = Db::name('qt_order_project')->where(['id' => $getData['order_id']])->find();
            $OrderprojectModel = new Orderproject();
            $res = $OrderprojectModel->start_project($orderProject['id'], $orderProject['engineer_id'], '2', $this->userInfo);
            //判断房间是否还有未支付的项目订单
            $noPayOrderProject = Db::name('qt_order_project')->where(['room_id' => $orderProject['room_id'], 'pay_status' => '0'])->find();
            if ($noPayOrderProject == null) {
                Db::name('qt_order')->where(['id' => $orderProject['order_id']])->update(['pay_status' => '2']);
            }
            if ($res['status']) {
                //下钟成功播报
                $voiceResult = VoiceService::createVoice('下钟成功');
                if ($voiceResult['code'] == 0) {
                    VoiceService::saveVoiceMsg($this->userInfo['store_id'], '下钟成功', $voiceResult['data'], '6', '3', $getData['engineer_id']);
                }
                //下钟动排
                $storeRule = Db::name('qt_queue_rule')->where(['type' => '1', 'store_id' => $this->userInfo['store_id']])->find();
                if ($storeRule['is_down_act'] == '1') {
                    $endSort = Db::name('qt_order_queue')
                        ->where(['store_id' => $this->userInfo['store_id']])
                        ->order('sort desc')
                        ->find();
                    Db::name('qt_order_queue')->where(['store_id' => $this->userInfo['store_id'], 'user_id' => $getData['engineer_id']])->update(['sort' => $endSort['sort'] + 1]);
                }
                //判断是否有多钟排位
                $manyQueueData = Db::name('qt_order_many_queue')
                    ->field('queue.*,rule.is_down_act')
                    ->alias('queue')
                    ->leftJoin('qt_many_queue_rule rule', 'rule.id = queue.many_queue_id')
                    ->where([
                        'queue.store_id' => $this->userInfo['store_id'],
                        'queue.user_id' => $getData['engineer_id'],
                        'queue.project_id' => $orderProject['project_id']
                    ])->find();
                if ($manyQueueData['is_down_act'] == '1') {
                    $endSort = Db::name('qt_order_many_queue')
                        ->where(['many_queue_id' => $manyQueueData['many_queue_id']])
                        ->max('sort');
                    Db::name('qt_order_many_queue')->where(['id' => $manyQueueData['id'],])->update(['sort' => $endSort + 1]);
                }
                $this->result('下钟成功', '', 200);
            } else {
                $this->result('下钟失败', $res['msg'], 204);
            }

        } else {
            $this->result('非法请求', '', 204);
        }
    }


    /**
     * 技师上班
     */
    public function go_work()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['engineer_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $update = Db::name('qt_users')->where('id', $getData['engineer_id'])->update(['work_status' => '1']);
            $find = Db::name('qt_order_queue')
                ->where('store_id', $this->userInfo['store_id'])
                ->where('user_id', $getData['engineer_id'])
                ->order('sort desc')
                ->find();
            //如果没有在排位里面先添加
            if (empty($find)) {
                $queue = Db::name('qt_order_queue')->where('store_id')->order('sort desc')->find();
                $sort = $queue['sort'] + 1;
                $insert = [
                    'store_id' => $this->userInfo['store_id'],
                    'user_id' => $getData['engineer_id'],
                    'sort' => $sort,
                    'day' => date('Y-m-d'),
                    'type_id' => date('Y-m-d'),
                    'created_time' => time(),
                    'status' => '1',
                ];
                Db::name('qt_order_queue')->insert($insert);
            }
            //增加打开记录
            $week = Carbon::now()->dayOfWeekIso;//星期
            $insertData['user_id'] = $getData['engineer_id'];
            $insertData['other_user_id'] = $this->userInfo['id'];
            $insertData['store_id'] = $this->userInfo['store_id'];
            $insertData['week'] = $week;
            $insertData['day'] = strtotime(date('Y-m-d'));
            $insertData['work_type'] = '1';
            $insertData['created_time'] = time();
            $insertData['type'] = '1';
            Db::name('qt_work_log')->insert($insertData);
            //处理技师排钟
            $storeRule = storeQueue($this->userInfo['store_id']);
            if ($storeRule['rule'] == '3') {
                //将该技师置头牌
                topSort($this->userInfo['store_id'], $getData['engineer_id']);
            }
            if ($update !== false) {
                $this->result('上班成功', '', 200);
            } else {
                $this->result('上班失败', '', 204);
            }

        } else {
            $this->result('非法请求', '', 204);
        }
    }

    /**
     * 技师下班
     */
    public function off_work()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['engineer_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $workStatus = Db::name('qt_users')->where('id', $getData['engineer_id'])->value('work_status');
            if ($workStatus != '1') {
                $this->result('该技师暂时不支持下班', '', 204);
            }
            $update = Db::name('qt_users')->where('id', $getData['engineer_id'])->update(['work_status' => '2']);
            //增加打开记录
            $week = Carbon::now()->dayOfWeekIso;//星期
            $insertData['user_id'] = $getData['engineer_id'];
            $insertData['other_user_id'] = $this->userInfo['id'];
            $insertData['store_id'] = $this->userInfo['store_id'];
            $insertData['week'] = $week;
            $insertData['day'] = strtotime(date('Y-m-d'));
            $insertData['work_type'] = '2';
            $insertData['created_time'] = time();
            $insertData['type'] = '1';
            Db::name('qt_work_log')->insert($insertData);
            if ($update !== false) {
                $this->result('下班成功', '', 200);
            } else {
                $this->result('下班失败', '', 204);
            }

        } else {
            $this->result('非法请求', '', 204);
        }
    }

    /**
     * 退技师
     */
    public function retreatEngineer()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['engineer_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $userInfo = $this->userInfo;
            $find = Db::name('qt_order_queue')
                ->where(['user_id' => $getData['engineer_id']])
                ->find();
            //退技师时间限制
            if ($find['start_time'] != null) {
                $time = (time() - $find['start_time']) / 60;
                $time = ceil($time);
                if ($this->storeInfo['back_engineer_block'] != '0') {
                    if ($time > $this->storeInfo['back_engineer_block']) {
                        $this->result('上钟超过设置时间，无法退技师', '', 204);
                    }
                }
            }
            //退技师支付状态限制
            $orderProject = Db::name('qt_order_project')->where(['id' => $find['order_project_id']])->find();
            if ($orderProject['pay_status'] == '1') {
                $this->result('该项目已经支付，无法退技师', '', 204);
            }
            if($orderProject['order_type'] != '5'){
                //退提成
                Db::name('qt_commission_log')->where(['type'=>'1','order_project_id'=>$orderProject['id']])->delete();
                $duanweiData = Db::name('qt_duanwei')
                    ->where("FIND_IN_SET(" . $getData['engineer_id'] . ",engineer_id)")
                    ->where(['project_id' => $orderProject['project_id']])
                    ->find();
                if (!empty($duanweiData)) {
                    //查找技师是否下了商品订单
                    $orderGoodsItem = Db::name('qt_product_order_item')
                        ->where(['goods_id' => $duanweiData['product_id'], 'room_id' => $find['room_id'], 'sale_id' => $getData['engineer_id'], 'business_type' => '5'])
                        ->find();
                    if (!empty($orderGoodsItem)) {
                        \app\common\model\Duanwei::delDuanweiPrice($orderGoodsItem['id']);
                    }
                }
            }
            Db::startTrans();
            try {
                //恢复技师原来位置
                $update['sort'] = empty($find['old_sort']) ? $find['sort'] : $find['old_sort'];
                //退手牌总金额
                HandCardM::decHandCardMoney($orderProject['id'],$orderProject['hand_card_id'],'1');
                //如果是加钟的，更新技师时间
                if($orderProject['order_type'] == '5'){
                    $project = Db::name('qt_project')->where(['id'=>$orderProject['project_id']])->find();
                    //查找头钟
                    $titleOrder = Db::name('qt_order_project')
                        ->where(['engineer_id'=>$getData['engineer_id'],'is_delete'=>'2'])
                        ->whereIn('status',['1','2','3'])
                        ->find();
                    //更新头钟下钟时间
                    $time = $orderProject['end_time'] - ($project['add_block_time'] * 60);
                    Db::name('qt_order_project')->where(['id'=>$titleOrder['id']])->update(['end_time'=>$time]);
                    //更新技师排位数据
                    Db::name('qt_order_queue')->where(['user_id'=>$getData['engineer_id']])->update(['end_time'=>$time]);
                    //更新加钟订单状态
                    Db::name('qt_order_project')
                        ->where('is_delete',2)
                        ->where(['id'=>$getData['order_project_id']])
                        ->update(['is_change'=>'2', 'status'=>'4','return_time'=>time()]);
                }else{
                    $update['room_id'] = null;
                    $update['project_id'] = null;
                    $update['order_project_id'] = null;
                    $update['start_time'] = null;
                    $update['end_time'] = null;
                    $update['real_time'] = null;
                    $update['order_user_id'] = null;
                    Db::name('qt_order_queue')->where(['user_id' => $getData['engineer_id']])->update($update);
                    //更新订单状态
                    Db::name('qt_order_project')->where('id', $find['order_project_id'])->update(['is_change' => '2', 'status' => '4', 'return_time' => time()]);
                    //更新房间状态
                    $roomQueue = Db::name('qt_order_queue')
                        ->where(['room_id' => $find['room_id']])
                        ->where('user_id', 'neq', $getData['engineer_id'])
                        ->find();
                    //如果没有其他技师更新房间状态
                    if (empty($roomQueue)) {
                        Db::name('qt_room')->where('id', $find['room_id'])->update(['status_id' => '10', 'retreat_time' => time()]);
                    } else {
                        Db::name('qt_room')->where('id', $find['room_id'])->update(['status_id' => $roomQueue['status']]);
                    }
                    //更新技师状态
                    Db::name('qt_users')->where('id', $getData['engineer_id'])->update(['work_status' => '1']);
                }
                //安排等位
                $waitRes = Db::name('qt_wait')
                    ->where(['store_id' => $this->storeInfo['id'], 'status' => '1', 'delay_time' => '0'])
                    ->where('room_id', 'neq', $find['room_id'])
                    ->order('is_first desc id desc')
                    ->find();
                if (!empty($waitRes)) {
                    //查找可以安排的技师
                    $data['man_num'] = 0;
                    $data['woman_num'] = 0;
                    $data['other_num'] = 0;
                    if ($waitRes['sex'] == '1') {
                        $data['man_num'] = $waitRes['number'];
                    }
                    if ($waitRes['sex'] == '2') {
                        $data['woman_num'] = $waitRes['number'];
                    }
                    if ($waitRes['sex'] == '3') {
                        $data['other_num'] = $waitRes['number'];
                    }
                    $data['project_id'] = $waitRes['project_id'];
                    $data['room_id'] = $waitRes['room_id'];
                    $data['hand_card_id'] = '';
                    $data['delay'] = 0;
                    $data['time_type'] = 1;
                    $data['order_type'] = 1;
                    $data['create_id'] = $userInfo['id'] ?? '';
                    $data['sale_id'] = $userInfo['id'] ?? '';
                    $orderModel = new \app\common\model\Order();
                    $code = $orderModel->create_order($data, $userInfo);
                    if ($code['code'] == '200') {
                        Db::name('qt_wait')->where(['id' => $waitRes['id']])->update(['status' => '2']);
                    }
                }
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('操作失败'.$exception->getFile().$exception->getLine().$exception->getMessage(), '', 204);
            }
            $this->result('操作成功', '', 200);


        } else {
            $this->result('非法请求', '', 204);
        }
    }


    /**
     * 客人退钟
     */
    public function delEngineer()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['engineer_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $find = Db::name('qt_order_queue')
                ->where(['user_id' => $getData['engineer_id']])
                ->find();
            $orderProject = Db::name('qt_order_project')->where('id', $find['order_project_id'])->find();
            try {
                Db::startTrans();
                //恢复技师原来位置
                if (empty($find['old_sort'])) {
                    $update['sort'] = $find['sort'];
                } else {
                    $update['sort'] = $find['old_sort'];
                }
                $update['room_id'] = null;
                $update['project_id'] = null;
                $update['order_project_id'] = null;
                $update['start_time'] = null;
                $update['end_time'] = null;
                $update['real_time'] = null;
                $update['order_user_id'] = null;
                Db::name('qt_order_queue')->where(['user_id' => $getData['engineer_id']])->update($update);
                //更新订单状态
                Db::name('qt_order_project')->where('id', $find['order_project_id'])->update(['is_change' => '2', 'status' => '4', 'return_time' => time()]);
                //更新房间状态
                Db::name('qt_room')->where('id', $orderProject['room_id'])->update(['status_id' => '10']);
                //更新技师状态
                Db::name('qt_users')->where('id', $getData['engineer_id'])->update(['work_status' => '1']);
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('操作失败', '', 204);
            }
            $this->result('操作成功', '', 200);


        } else {
            $this->result('非法请求', '', 204);
        }
    }


    /**
     * 催技师
     */
    public function urgeEngineer()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['engineer_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $find = Db::name('qt_order_queue')
                ->where(['user_id' => $getData['engineer_id']])
                ->find();
            $orderProject = Db::name('qt_order_project')->where('id', $find['order_project_id'])->find();
            $content = $orderProject['name'] . '在' . date('Y-m-d H:i:s') . '预计结束' . '现在已经超时,请及时下钟';
            $insert = [
                'user_id' => $this->userInfo['id'],
                'to_user_id' => $getData['engineer_id'],
                'title' => '您有一条催钟提醒！',
                'room_id' => $orderProject['room_id'],
                'order_id' => $orderProject['id'],
                'content' => $content,
                'status' => '1',
                'read' => '0',
                'type' => '1',
                'created_time' => time(),
            ];
            $save = Db::name('qt_message')->insert($insert);
            //催钟成功播报
            $voiceResult = VoiceService::createVoice($content);
            if ($voiceResult['code'] == 0) {
                VoiceService::saveVoiceMsg($this->userInfo['store_id'], $content, $voiceResult['data'], '8', '3', $getData['engineer_id']);
            }
            if ($save) {
                $this->result('操作成功', '', 200);
            }
            $this->result('系统繁忙，请稍后再试！', '', 204);
        } else {
            $this->result('非法请求', '', 204);
        }
    }


    /**
     * 撤销下钟
     */
    public function revokeClock()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['engineer_id'])) {
                $this->result('缺少参数', '', 204);
            }
            //技师空闲状态不能撤销
            $orderProject = Db::name('qt_order_project')->where('engineer_id', $getData['engineer_id'])->order('id desc')->find();
            if ($orderProject['pay_status'] == '1') {
                $this->result('当前项目已经结账了，暂时不能撤销', '', 204);
            }
            if (empty($orderProject)) {
                $this->result('当前技师没有上钟项目，不需要撤销哦', '', 204);
            }
            $engineerStatus = Db::name('qt_users')->where('id', $orderProject['engineer_id'])->value('work_status');
            if ($engineerStatus != '1') {
                $this->result('该技师状态有问题，暂时不能撤销', '', 204);
            }
            //技师在其他房间上钟不能撤销
            $engineerQueue = Db::name('qt_order_queue')->where('order_project_id', $orderProject['id'])->find();
            if ($orderProject['room_id'] != $engineerQueue['room_id'] && $engineerQueue['status'] == '3') {
                $this->result('该技师已在其他房间上钟，暂时不能撤销', '', 204);
            }
            try {
                //更新项目订单状态
                Db::name('qt_order_project')->where('id', $orderProject['id'])->update(['status' => '2', 'real_end_time' => null]);
                //更新房间状态
                Db::name('qt_room')->where('id', $orderProject['room_id'])->update(['status_id' => '3']);
                //更新技师状态
                Db::name('qt_users')->where('id', $orderProject['engineer_id'])->update(['work_status' => '4']);
                //更新技师状态
                Db::name('qt_order_queue')->where('user_id', $orderProject['engineer_id'])
                    ->update([
                        'real_time' => null,
                        'start_time' => $orderProject['start_time'],
                        'end_time' => $orderProject['end_time'],
                        'room_id' => $orderProject['room_id'],
                        'project_id'=>$orderProject['project_id'],
                        'order_project_id'=>$orderProject['id'],
                    ]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result('系统繁忙，请稍后再试！', '', 204);
            }
            $this->result('操作成功', '', 200);
        } else {
            $this->result('非法请求', '', 204);
        }
    }


    /**
     * 更换技师
     */
    public function change_engineer()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $find = Db::name('qt_order_queue')->where(['user_id' => $getData['engineer_id']])->find();
            //项目子订单
            $orderProject = Db::name('qt_order_project')->where('id', $find['order_project_id'])->find();

            //退技师限制
            if ($orderProject['start_time'] != null) {
                $time = (time() - $orderProject['start_time']) / 60;
                $time = ceil($time);
                if ($this->storeInfo['change_engineer_block'] != '0') {
                    if ($time > $this->storeInfo['change_engineer_block']) {
                        $this->result('上钟超过设置时间，无法更换技师', '', 204);
                    }
                }
            }
            if ($orderProject['start_time'] == null) {
                $startTime = time();
            } else {
                $startTime = $orderProject['start_time'];
            }

            //删除提成记录
            Db::name('qt_commission_log')->where(['order_project_id' => $orderProject['id'], 'type' => '1'])->delete();



            //有手牌减掉手牌金额
            if($orderProject['hand_card_id'] != null){
                $handCard = new HandCard();
                $handCard::decHandCardMoney($orderProject,$orderProject['hand_card_id'],'1');
            }

            if ($getData['type'] == '1') {
                //新订单信息
                $newOrderProjectInsert = [
                    'store_id' => $orderProject['store_id'],
                    'name' => $orderProject['name'],
                    'created_order_id' => $orderProject['created_order_id'],
                    'order_id' => $orderProject['order_id'],
                    'start_time' => $startTime,
                    'project_id' => $orderProject['project_id'],
                    'room_id' => $orderProject['room_id'],
                    'hand_card_id' => $orderProject['hand_card_id'],
                    'sale_id' => $orderProject['sale_id'],
                    'order_type' => '1',
                    'num' => $orderProject['num'],
                    'price' => $orderProject['price'],
                    'status' => '1',
                    'is_add' => '1',
                    'is_change' => '1',
                    'created_time' => time()
                ];
                //安排技师
                $orderProjectId = Db::name('qt_order_project')->insertGetId($newOrderProjectInsert);
                $project = Db::name('qt_order_project')->where('id', $orderProjectId)->find();
                Db::name('qt_order_detail')->where(['order_project_id' => $orderProject['id']])->update(['status' => '2']);
                //查询多种排位规则
                $value = Db::name('qt_many_queue_rule')
                    ->where("FIND_IN_SET(" . $orderProject['project_id'] . ",project_ids)")
                    ->find();
                if (!empty($value)) {
                    $orderModel = new Order();
                    $orderModel->many_scheduling($project, $getData['sex'], $this->storeInfo, $value['id']);
                } else {
                    $orderModel = new Order();
                    $orderModel->scheduling($project, $getData['sex'], $this->storeInfo);
                }
                //更新老项目数据
                Db::name('qt_order_project')->where(['id' => $orderProject['id']])->update(['status' => '4', 'is_change' => '2']);
                $duanweiData = Db::name('qt_duanwei')
                    ->where("FIND_IN_SET(" . $getData['engineer_id'] . ",engineer_id)")
                    ->where(['project_id' => $orderProject['project_id']])
                    ->find();
                if (!empty($duanweiData)) {
                    //查找技师是否下了商品订单
                    $orderGoodsItem = Db::name('qt_product_order_item')
                        ->where([
                            'goods_id' => $duanweiData['product_id'],
                            'room_id' => $find['room_id'],
                            'sale_id' => $getData['engineer_id'],
                            'business_type' => '5'
                        ])
                        ->find();
                    if (!empty($orderGoodsItem)) {
                        \app\common\model\Duanwei::delDuanweiPrice($orderGoodsItem['id']);
                    }
                }
                //更新排位
                Db::name('qt_order_queue')->where(['user_id' => $getData['engineer_id']])
                    ->update([
                        'room_id' => null,
                        'project_id' => null,
                        'order_project_id' => null,
                        'start_time' => null,
                        'end_time' => null,
                        'sort' => $find['old_sort'],
                        'order_user_id' => 0,
                        'return_time' => time(),
                        'return_room' => $orderProject['room_id'],
                    ]);
                Db::name('qt_users')->where(['id' => $getData['engineer_id']])->update(['work_status' => '1']);
                //修改房间状态
                Db::name('qt_room')->where(['id' => $orderProject['room_id']])->update(['status_id' => '2', 'retreat_time' => time()]);


                //插入订单详情
                $orderDetailInsert = [
                    'store_id' => $orderProject['store_id'],
                    'room_id' => $orderProject['room_id'],
                    'engineer_id' => $getData['engineer_id'],
                    'hand_card_id' => $orderProject['hand_card_id'],
                    'check_out_id' => '',
                    'project_id' => $orderProject['project_id'],
                    'order_project_id' => $orderProjectId,
                    'create_user_id' => $orderProject['created_order_id'],
                    'order_type' => 1,
                    'create_time' => time(),
                ];
                Db::name('qt_order_detail')->insert($orderDetailInsert);

                $this->result('操作成功', '', 200);
            } else {
                //点钟
                if (empty($find)) {
                    $this->result('项目不存在', '', 204);
                }
                $nowproject = Db::name('qt_order_project')->where('id', $find['order_project_id'])->find();
                if ($nowproject['start_time'] != null) {
                    if ((time() - $nowproject['start_time']) >= 600) {
                        $this->result('超过十分钟无法更换技师', '', 204);
                    }
                }
                $project['order_id'] = $nowproject['order_id'];
                $project['room_id'] = $orderProject['room_id'];
                $project['hand_card_id'] = $nowproject['hand_card_id'];
                $project['order_type'] = $getData['order_type'];
                $project['status'] = '1';
                $project['project_id'] = $orderProject['project_id'];
                $project['store_id'] = $nowproject['store_id'];
                $project['name'] = $nowproject['name'];
                $project['price'] = $nowproject['price'];
                $project['payment_price'] = $nowproject['price'];
                $project['created_time'] = time();
                $project['is_change'] = '1';
                Db::name('qt_order_project')->where('id', $find['order_project_id'])->update(['status' => '4', 'is_change' => '3']);
                $neworder_project_id = Db::name('qt_order_project')->insertGetId($project);
                $this->find($nowproject['id'], $orderProject['project_id'], $neworder_project_id, $getData['change_engineer_id']);

                //插入订单详情
                $orderDetailInsert = [
                    'store_id' => $orderProject['store_id'],
                    'room_id' => $orderProject['room_id'],
                    'engineer_id' => $getData['engineer_id'],
                    'hand_card_id' => $orderProject['hand_card_id'],
                    'check_out_id' => '',
                    'project_id' => $orderProject['project_id'],
                    'order_project_id' => $neworder_project_id,
                    'create_user_id' => $orderProject['created_order_id'],
                    'order_type' => $getData['order_type'],
                    'create_time' => time(),
                ];
                Db::name('qt_order_detail')->insert($orderDetailInsert);

                $this->result('更新成功', '', 200);
            }

        } else {
            $this->result('非法请求', '', 204);
        }
    }


    /**
     * 查找合适的技师
     * @param $old_order_project_id [旧订单ID]
     * @param $project_id [项目ID]
     * @param $new_order_project_id [新订单ID]
     * @param $engineer_id [更换技师ID]
     * @return array
     */
    public function find($old_order_project_id, $project_id, $new_order_project_id, $engineer_id)
    {
        //查找当前技师是否在空闲
        $orderQueue = Db::name('qt_users')->where('id', $engineer_id)->find();
        if ($orderQueue['work_status'] != '1') {
            $this->result('当前技师不在空闲状态，暂时无法更换', '', 204);
        }
        $oldorder = Db::name('qt_order_project')->where('id', $old_order_project_id)->find();
//        $bigorder = Order::where('id',$oldorder['order_id'])->find();
        //最新排序
        $project = Project::where('id', $project_id)->find();
        //新项目
        $newOrderProject = Db::name('qt_order_project')->where('id', $new_order_project_id)->find();
        if ($newOrderProject['order_type'] == '3') {
            //call钟
            $rale = $project['call_block_rate'];
        } else if ($newOrderProject['order_type'] == '2') {
            //点钟
            $rale = $project['dot_block_rate'];
        }
        //老技师数据
        $oldQueue = Db::name('qt_order_queue')->where('user_id', $oldorder['engineer_id'])->find();
//        try{
//            Db::startTrans();
        //切换旧的技师排序
        Db::name('qt_order_queue')
            ->where('user_id', $oldorder['engineer_id'])
            ->where('order_project_id', $oldorder['id'])
            ->update(
                [
                    'room_id' => null,
                    'project_id' => null,
                    'order_project_id' => null,
                    'order_user_id' => null,
                    'status' => '1',
                    'sort' => $oldQueue['old_sort'],
                ]
            );
        //更新技师状态
        Db::name('qt_users')->where('id', $oldorder['engineer_id'])->update(['work_status' => '1']);
        //更新新技师状态
        Db::name('qt_users')->where('id', $engineer_id)->update(['work_status' => '5']);
        //删除记录
        Db::name('qt_commission_log')
            ->where(['order_project_id' => $oldorder['id'], 'type' => '1'])
            ->delete();
        //修改新的技师
        Db::name('qt_order_queue')->where('user_id', $engineer_id)->update(
            [
                'room_id' => $oldorder['room_id'],
                'project_id' => $project_id,
                'order_project_id' => $new_order_project_id,
                'order_user_id' => $newOrderProject['sale_id'],
                'status' => '2',
            ]
        );
        //修改房间状态
        Db::name('qt_room')->where(['id' => $oldorder['room_id']])->update(['status_id' => '2', 'retreat_time' => time()]);
        //插入订单详情记录
        $orderDetailInsert = [
            'store_id' => $newOrderProject['store_id'],
            'room_id' => $newOrderProject['room_id'],
            'engineer_id' => $engineer_id,
            'hand_card_id' => $newOrderProject['hand_card_id'],
            'check_out_id' => '',
            'project_id' => $newOrderProject['project_id'],
            'order_project_id' => $newOrderProject['id'],
            'create_user_id' => $this->userInfo['id'],
            'order_type' => $newOrderProject['order_type'],
            'create_time' => time(),
        ];
        Db::name('qt_order_detail')->insert($orderDetailInsert);
        Db::name('qt_order_detail')->where(['order_project_id' => $oldorder['id']])->update(['status' => '2']);
        //新增订单提成明细表
        $commion_log = array(
            'store_id' => $newOrderProject['store_id'],
            'user_id' => $engineer_id,
            //'cashier_id'=>$arr['saler_id'],
            'member' => '',
            'money' => $project['price'],
            'payment_price' => $project['price'],
            'commission' => $project['price'] * $rale / 100,
            'rale' => $rale,
            'product_id' => $project_id,
            'type' => '1',
            'pay_type' => '',
            'created_time' => time(),
            'room_id' => $newOrderProject['room_id'],
            'is_pay' => '1',
        );
        CommissionLog::create($commion_log);
        //修改分订单的技师id
        Db::name('qt_order_project')->where('id', $new_order_project_id)->update(
            [
                'engineer_id' => $engineer_id,
                'status' => '1',
            ]
        );
//            Db::commit();
//        }catch (Exception $exception){
//            Db::rollback();
//            $this->result('系统繁忙，请稍后再试','',204);
//        }


    }

    /**
     * 技师加钟
     */
    public function addClock()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['project_id']) || empty($getData['num'])) {
                $this->result('缺少参数', '', 204);
            }
            $find = Db::name('qt_order_queue')
                ->where(['user_id' => $getData['engineer_id']])
                ->find();
            $orderProject = Db::name('qt_order_project')->where('id', $find['order_project_id'])->find();
            $project = Db::name('qt_project')->where('id', $getData['project_id'])->find();
            $add = Db::name('qt_users')->where('id', $getData['engineer_id'])->value('is_add');
            //下新项目
            $insertOrderProject = [
                'store_id' => $orderProject['store_id'],
                'name' => $project['name'],
                'created_order_id' => $this->userInfo['id'],
                'creater_room' => $orderProject['creater_room'],
                'order_id' => $orderProject['order_id'],
                'engineer_id' => $orderProject['engineer_id'],
                'sale_id' =>  $this->userInfo['id'],
                'project_id' => $getData['project_id'],
                'room_id' => $orderProject['room_id'],
                'hand_card_id' => $orderProject['hand_card_id'],
                'old_card_id' => $orderProject['old_card_id'],
                'order_type' => '5',
                'num' => $getData['num'],
                'price' => $project['add_block_price']*$getData['num'],
                'status' => 2,
                'is_add' => $add,
                'start_time' => $orderProject['start_time'],
                'end_time' => $orderProject['end_time'] + ($project['add_block_time'] * 60 * $getData['num']),
                'is_change' => '1',
                'created_time' => time(),
            ];
            try {
                //更新项目订单状态
                Db::name('qt_order_project')
                    ->where('id', $orderProject['id'])
                    ->update([
                        'end_time' => $orderProject['end_time'] + ($project['add_block_time'] * 60),
                        'status' => '2'
                    ]);
                $newOrderId = Db::name('qt_order_project')->insertGetId($insertOrderProject);
                $orderData = Db::name('qt_order_project')->where(['id' => $newOrderId])->find();
                Project::getCommission($orderData, $this->storeInfo);
                Db::name('qt_order_queue')
                    ->where('user_id', $orderProject['engineer_id'])
                    ->update([
                        'end_time' => $orderProject['end_time'] + ($project['add_block_time'] * 60)
                    ]);
                //插入订单详情
                $orderDetailInsert = [
                    'store_id' => $orderProject['store_id'],
                    'room_id' => $orderProject['room_id'],
                    'engineer_id' => $getData['engineer_id'],
                    'hand_card_id' => $orderProject['hand_card_id'],
                    'check_out_id' => '',
                    'project_id' => $orderProject['project_id'],
                    'order_project_id' => $newOrderId,
                    'create_user_id' => $orderProject['created_order_id'],
                    'order_type' => 1,
                    'create_time' => time(),
                ];
                Db::name('qt_order_detail')->insert($orderDetailInsert);

                if($orderProject['hand_card_id'] != null){
                    //手牌增加金额
                    HandCardM::incHandCardMoney($newOrderId,$orderProject['hand_card_id'],1);
                }

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result('加钟失败', '', 204);
            }
            $this->result('加钟成功', '', 200);


        }
    }


    /**
     * 技师自由开单
     */
    public function freeBilling()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['project_id']) || empty($getData['num']) || empty($getData['engineer_id']) || empty($getData['room_id'])) {
                $this->result('缺少参数', '', 204);
            }
            //判断房间是否开房
            $room = Db::name('qt_room')->where(['id' => $getData['room_id']])->find();
            $statusArray = ['2', '3', '10'];
            if (!in_array($room['status_id'], $statusArray)) {
                $this->result('房间状态有问题，暂不支持下单', '', 204);
            }
            $userInfo = Db::name('qt_users')->where(['id' => $getData['engineer_id']])->find();
            if ($userInfo['work_status'] != '1') {
                $this->result('当前技师状态有问题，暂不支持下单', '', 204);
            }

            //判断技师是否可以自由开单
            $res = Db::name('qt_user_project')
                ->alias('up')
                ->leftJoin('qt_project p', 'p.id = up.project_id')
                ->leftJoin('qt_users_auth au', 'au.engineer_id = up.engineer_id')
                ->where(['up.engineer_id' => $getData['engineer_id'], 'p.is_free_order' => '1', 'au.is_open' => '1'])
                ->find();
            if (empty($res)) {
                $this->result('当前技术没有自由开单权限', '', 204);
            }
            //项目信息
            $projectRes = Db::name('qt_project')->where('id', $getData['project_id'])->find();
            //判断总订单是否存在
            $orderCheck = Db::name('qt_order')->where(['room_id' => $getData['room_id'], 'pay_status' => '1'])->find();
            try {
                if (empty($orderCheck)) {
                    $orderInsert['order_no'] = ordersn();
                    $orderInsert['store_id'] = $projectRes['store_id'];
                    $orderInsert['room_id'] = $getData['room_id'];
                    $orderInsert['total_num'] = '1';
                    $orderInsert['total_price'] = $projectRes['price'];
                    $orderInsert['status'] = '1';
                    $orderInsert['order_type'] = '1';
                    $orderInsert['delay'] = 0;
                    $orderInsert['time_type'] = 1;
                    $orderInsert['created_time'] = time();
                    $orderModel = new Order();
                    $orderRes = $orderModel::create($orderInsert);
                    $orderId = $orderRes->id;
                } else {
                    $orderId = $orderCheck['id'];
                }
                //生成订单附表
                $orderProjectInsert = [
                    'name' => $projectRes['name'],
                    'created_order_id' => $this->userInfo['id'],
                    'order_id' => $orderId,
                    'engineer_id' => $this->userInfo['id'],
                    'project_id' => $getData['project_id'],
                    'room_id' => $getData['room_id'],
                    'order_type' => '1',
                    'num' => '1',
                    'price' => $projectRes['price'],
                    'store_id' => $projectRes['store_id'],
                    'creater_room' => '',
                    'created_time' => time(),
                    'sale_id' => $this->userInfo['id'],
                ];
                $orderProjectId = Db::name('qt_order_project')->insertGetId($orderProjectInsert);
                //子订单信息
                $orderProject = Db::name('qt_order_project')->where('id', $orderProjectId)->find();
                //用户信息
                $userInfo = Db::name('qt_users')->where(['id' => $getData['engineer_id']])->find();
                //最大的sort
                $endSort = Db::name('qt_order_queue')->where(['store_id' => $orderProject['store_id']])->max('sort');
                try {
                    Db::startTrans();
                    //修改订单状态
                    Db::name('qt_order_project')->where(['id' => $orderProject['id']])->update(['engineer_id' => $getData['engineer_id']]);
                    //更新技师状态
                    Db::name('qt_users')->where('id', $getData['engineer_id'])->update(['work_status' => '5', 'room_id' => $getData['room_id']]);
                    //更新房间订单号
                    Db::name('qt_room')->where(['id' => $getData['room_id']])->update(['order_id' => $orderProject['order_id']]);
                    //更新技师排班数据
                    $updateQueue['room_id'] = $getData['room_id'];
                    $updateQueue['project_id'] = $getData['project_id'];
                    $updateQueue['order_project_id'] = $orderProject['id'];
                    $updateQueue['order_user_id'] = $orderProject['created_order_id'];
                    $updateQueue['day'] = date("Y-m-d");
                    $updateQueue['type_id'] = $userInfo['type_id'];
                    $updateQueue['status'] = '2';
                    $updateQueue['sort'] = $endSort + 1;
                    Db::name('qt_order_queue')->where(['id' => $getData['engineer_id']])->update($updateQueue);
                    Db::commit();
                } catch (Exception $exception) {
                    Db::rollback();
                    $this->result('下单失败', '', 204);
                }
            } catch (Exception $e) {
                print $e->getMessage();
                exit();
            }
            $this->result('下单成功', '', 200);
        }
    }


    /**
     * 订单派技师
     * @param $order [订单信息]
     * @param $type [订单类型]
     */
    public function scheduling($order, $sex, $engineer = '')
    {
        if ($sex == '3') {
            $sql = Db::name('qt_user_project')
                ->alias('up')
                ->leftJoin('qt_users u', 'u.id = up.engineer_id')
                ->where('up.project_id', $order['project_id'])
                ->where('u.work_status', '1');
        } elseif ($sex == '1') {
            $sql = Db::name('qt_user_project')
                ->alias('up')
                ->leftJoin('qt_users u', 'u.id = up.engineer_id')
                ->where('up.project_id', $order['project_id'])
                ->where('u.work_status', '1')
                ->where('u.sex', $sex);
        } elseif ($sex == '2') {
            $sql = Db::name('qt_user_project')
                ->alias('up')
                ->leftJoin('qt_users u', 'u.id = up.engineer_id')
                ->where('up.project_id', $order['project_id'])
                ->where('u.work_status', '1')
                ->where('u.sex', $sex);
        } elseif ($sex == '4') {
            $sql = Db::name('qt_user_project')
                ->alias('up')
                ->leftJoin('qt_users u', 'u.id = up.engineer_id')
                ->where('up.project_id', $order['project_id'])
                ->where('u.id', $engineer);
        }
        //获取可做项目的所有空闲技师
        $userIds = $sql->group('up.engineer_id')->column('up.engineer_id');
        if ($order['order_type'] == '1') {
            //查找今日未排班的技师
            $sort = Db::name('qt_scheduling_queue')
                ->whereIn('engineer_id', $userIds)
                ->where(['current' => '1'])
                ->order('sort asc')
                ->find();
            //如果有的话排技师，直接排技师
            if (!empty($sort)) {
                try {
                    Db::startTrans();
                    //修改订单状态
                    Db::name('qt_order_project')->where(['id' => $order['id']])->update(['engineer_id' => $sort['engineer_id']]);
                    //更新技师状态
                    Db::name('qt_users')->where('id', $sort['engineer_id'])->update(['work_status' => '5', 'room_id' => $order['room_id']]);
                    //更新默认排序
                    Db::name('qt_scheduling_queue')->where('engineer_id', $sort['engineer_id'])->update(['current' => '2']);
                    //更新房间订单号
                    Db::name('qt_room')->where(['id' => $order['room_id']])->update(['order_id' => $order['order_id'], 'status_id' => '2']);
                    $engineerOrderQueue = Db::name('qt_order_queue')->where(['user_id' => $sort['engineer_id']])->find();
                    if (empty($engineerOrderQueue)) {
                        //上钟表中加数据
                        $orderQueue['store_id'] = $order['store_id'];
                        $orderQueue['user_id'] = $sort['engineer_id'];
                        $orderQueue['room_id'] = $order['room_id'];
                        $orderQueue['project_id'] = $order['project_id'];
                        $orderQueue['order_project_id'] = $order['id'];
                        $orderQueue['order_user_id'] = $order['created_order_id'];
                        $orderQueue['sort'] = $sort['sort'] + 1;
                        $orderQueue['day'] = date("Y-m-d");
                        $orderQueue['type_id'] = $sort['type_id'];
                        $orderQueue['status'] = '2';
                        $orderQueue['created_time'] = time();
                        Db::name('qt_order_queue')->insert($orderQueue);
                    } else {
                        $updateQueue['room_id'] = $order['room_id'];
                        $updateQueue['project_id'] = $order['project_id'];
                        $updateQueue['order_project_id'] = $order['id'];
                        $updateQueue['order_user_id'] = $order['created_order_id'];
                        $updateQueue['day'] = date("Y-m-d");
                        $updateQueue['type_id'] = $sort['type_id'];
                        $updateQueue['status'] = '2';
                        Db::name('qt_order_queue')->where(['id' => $engineerOrderQueue['id']])->update($updateQueue);
                    }

                    Db::commit();
                } catch (Exception $exception) {
                    Db::rollback();
                    return ['code' => 204, 'msg' => '技师排班失败'];
                }
            } else {
                //查找已经在排队中的技师
                $sort = Db::name('qt_order_queue')->whereIn('user_id', $userIds)->order('id asc')->find();
                //修改订单状态
                Db::name('qt_order_project')->where(['id' => $order['id']])->update(['engineer_id' => $sort['user_id']]);
                //更新技师状态
                Db::name('qt_users')->where('id', $sort['user_id'])->update(['work_status' => '5', 'room_id' => $order['room_id']]);
                //更新房间订单号
                Db::name('qt_room')->where(['id' => $order['room_id']])->update(['order_id' => $order['order_id'], 'status_id' => '2']);
                //更新符合条件的技师信息
                Db::name('qt_order_queue')->where('user_id', $sort['user_id'])->update([
                    'sort' => $sort['sort'] + 1,
                    'room_id' => $order['room_id'],
                    'project_id' => $order['project_id'],
                    'order_project_id' => $order['id'],
                    'status' => '2'
                ]);
            }
        } else {
            Db::name('qt_order_project')->where(['id' => $order['id']])->update(['engineer_id' => $engineer]);
            Db::name('qt_users')->where('id', $engineer)->update(['work_status' => '5', 'room_id' => $order['room_id']]);
            //更新房间订单号
            Db::name('qt_room')->where(['id' => $order['room_id']])->update(['order_id' => $order['order_id'], 'status_id' => '2']);
            //查找最大的排序
            $sort = Db::name('qt_order_queue')
                ->whereIn('user_id', $userIds)
                ->where(['status' => '1'])
//                ->where('day',date('Y-m-d'))
                ->order('sort desc')
                ->find();
            //更新符合条件的技师信息
            $engineerRes = Db::name('qt_order_queue')->where('user_id', $engineer)->find();
            if ($engineerRes['status'] != '1') {
                return ['code' => 204, 'msg' => '该技师未处于空闲状态'];
            }
            Db::name('qt_order_queue')
                ->where('user_id', $engineer)
//                ->where('day',date('Y-m-d'))
                ->update([
                    'sort' => $sort['sort'] + 1,
                    'room_id' => $order['room_id'],
                    'project_id' => $order['project_id'],
                    'order_project_id' => $order['order_id'],
                    'status' => '2'
                ]);
        }
    }


    /**
     * 获取正在上钟的项目
     */
    public function technician()
    {
        if ($this->request->isPost()) {
            $data = Db::name('qt_order_queue')
                ->field('oq.id,r.name as room_name,u.work_number,p.name as project_name,p.price,p.time,oq.start_time,op.hand_card_id,oq.end_time')
                ->alias('oq')
                ->where(['oq.store_id' => $this->userInfo['store_id']])
                ->whereNotNull('oq.start_time')
                ->leftJoin('qt_room r', 'r.id = oq.room_id')
                ->leftJoin('qt_project p', 'p.id = oq.project_id')
                ->leftJoin('qt_order_project op', 'op.id = oq.order_project_id')
                ->leftJoin('qt_users u', 'u.id = oq.user_id')
                ->select();
            foreach ($data as $key => $value) {
                $time = $value['end_time'] - time();
                $endTime = bcdiv($time, 60, 0);
                $data[$key]['shenyu'] = $endTime;
                $data[$key]['hand_card_name'] = Db::name('qt_hand_card')->where('id', $value['hand_card_id'])->value('name');
            }
            $this->result('查询成功', $data, 200);
        }
    }


    /**
     * 更换项目
     */
    public function change_project()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            //老项目订单
            $orderProject = Db::name('qt_order_project')->where('id', $getData['order_project_id'])->find();
            if ($orderProject['project_id'] == $getData['project_id']) {
                $this->result('所换项目与原来一致，请重新选择', '', 204);
            }
            //新项目
            $newProject = Db::name('qt_project')->where('id', $getData['project_id'])->find();
            $oldProject = Db::name('qt_project')->where('id', $orderProject['project_id'])->find();
            if (!empty($orderProject['start_time'])) {
                $startTime = $orderProject['start_time'];
                if ($newProject['time'] > $oldProject['time']) {
                    $ceil = $newProject['time'] - $oldProject['time'];
                    $endTime = $orderProject['end_time'] + ($ceil * 60);
                } else {
                    $ceil = $oldProject['time'] - $newProject['time'];
                    $endTime = $orderProject['end_time'] - ($ceil * 60);
                }
            } else {
                $startTime = null;
                $endTime = null;
            }
            //新订单信息
            $newOrderProjectInsert = [
                'store_id' => $orderProject['store_id'],
                'name' => $newProject['name'],
                'old_name' => $oldProject['name'],
                'created_order_id' => $orderProject['created_order_id'],
                'order_id' => $orderProject['order_id'],
                'engineer_id' => $getData['engineer_id'],
                'project_id' => $getData['project_id'],
                'room_id' => $orderProject['room_id'],
                'hand_card_id' => $orderProject['hand_card_id'],
                'order_type' => $orderProject['order_type'],
                'num' => $orderProject['num'],
                'price' => $newProject['price'],
                'status' => $orderProject['status'],
                'is_add' => '1',
                'is_change' => '1',
                'created_time' => time(),
                'sale_id' => $this->userInfo['id'],
                'start_time' => $startTime,
                'end_time' => $endTime,
            ];
            //插入新项目
            $newProjectId = Db::name('qt_order_project')->insertGetId($newOrderProjectInsert);
            //插入订单详情记录
            $orderDetailInsert = [
                'store_id' => $orderProject['store_id'],
                'room_id' => $orderProject['room_id'],
                'engineer_id' => $getData['engineer_id'],
                'hand_card_id' => $orderProject['hand_card_id'],
                'check_out_id' => '',
                'project_id' => $getData['project_id'],
                'order_project_id' => $newProjectId,
                'create_user_id' => $this->userInfo['id'],
                'order_type' => $orderProject['order_type'],
                'create_time' => time(),
            ];
            Db::name('qt_order_detail')->insert($orderDetailInsert);
            Db::name('qt_order_detail')->where(['order_project_id' => $getData['order_project_id']])->update(['status' => '2']);
            //新增段位费
            Duanwei::DuanweiPrice($getData['engineer_id'], $getData['project_id'], $orderProject['room_id']);
            //更新老项目数据
            Db::name('qt_order_project')->where(['id' => $getData['order_project_id']])->update(['status' => '5', 'is_change' => '3']);
            if ($startTime == null) {
                $workStatus = '5';
                $queueStatus = '2';
            } else {
                $workStatus = '4';
                $queueStatus = '3';
            }
            Db::name('qt_order_queue')
                ->where(['user_id' => $getData['engineer_id']])
                ->update([
                    'old_name' => $orderProject['name'],
                    'start_time' => $startTime,
                    'status' => $queueStatus,
                    'end_time' => $endTime,
                    'room_id' => $orderProject['room_id'],
                    'order_project_id' => $newProjectId
                ]);
            Db::name('qt_users')->where(['id' => $orderProject['engineer_id']])->update(['work_status' => $workStatus]);
            //判断接待提成规则
            //1=按下单人项目不管技师做什么项目，2=按技师上钟项目不管下单人下什么项目，3=下单人下单项目和技师上钟项目必须相同才有提成
            if ($this->storeInfo['receiver_order_commission_type'] == '2') {
                //删除之前的提成并插入新的接待提成和技师提成
                Db::startTrans();
                try {
                    //删除订单提成
                    Db::name('qt_commission_log')->where(['type' => '1', 'order_project_id' => $orderProject['id']])->delete();
                    //插入新的提成
                    $project = Db::name('qt_project')->where('id', $getData['project_id'])->find();
                    //普通提成
                    $commission = new OrdinaryService();
                    $commission = $commission->showCommission('1', '1', $project);
                    //计算接待提成
                    $receiver = new ReceiverService();
                    $receiver = $receiver->showCommission('1', '1', $project);
                    if ($this->storeInfo['floor_commission_type'] == '1') {
                        $cashierId = $orderProject['created_order_id'];
                    } else {
                        $cashierId = $orderProject['created_order_id'];
                    }
                    $insert = [
                        'store_id' => $this->storeInfo['id'],
                        'cashier_id' => $cashierId,//接待人
                        'user_id' => $getData['engineer_id'],//技师
                        'room_id' => $orderProject['room_id'],
                        'money' => $newProject['price'],
                        'commission' => $commission,//技师提成
                        'receiver' => $receiver,//接待提成
                        'product_id' => $orderProject['project_id'],
                        'type' => '1',
                        'created_time' => time(),
                        'is_pay' => '1',
                        'order_project_id' => $newProjectId,
                        'status' => $orderProject['order_type'],
                        'is_add' => $orderProject['order_type'],
                    ];
                    Db::name('qt_commission_log')->insert($insert);
                    //安排等位
                    $waitRes = Db::name('qt_wait')
                        ->where(['store_id' => $this->userInfo['id'], 'status' => '1', 'delay_time' => '0'])
                        ->where('room_id', 'neq', $orderProject['room_id'])
                        ->order('is_first desc id desc')
                        ->find();
                    if (!empty($waitRes)) {
                        //查找可以安排的技师
                        $data['man_num'] = 0;
                        $data['woman_num'] = 0;
                        $data['other_num'] = 0;
                        if ($waitRes['sex'] == '1') {
                            $data['man_num'] = $waitRes['number'];
                        }
                        if ($waitRes['sex'] == '2') {
                            $data['woman_num'] = $waitRes['number'];
                        }
                        if ($waitRes['sex'] == '3') {
                            $data['other_num'] = $waitRes['number'];
                        }
                        $data['project_id'] = $waitRes['project_id'];
                        $data['room_id'] = $waitRes['room_id'];
                        $data['hand_card_id'] = '';
                        $data['delay'] = 0;
                        $data['time_type'] = 1;
                        $data['order_type'] = 1;
                        $data['create_id'] = $userInfo['id'] ?? '';
                        $orderModel = new \app\common\model\Order();
                        $code = $orderModel->create_order($data, $userInfo);
                        if ($code['code'] == '200') {
                            Db::name('qt_wait')->where(['id' => $waitRes['id']])->update(['status' => '2']);
                        }
                    }
                    //处理段位费
                    $duanweiData = Db::name('qt_duanwei')
                        ->where("FIND_IN_SET(" . $getData['engineer_id'] . ",engineer_id)")
                        ->where(['project_id' => $orderProject['project_id']])
                        ->find();
                    if (!empty($duanweiData)) {
                        //查找技师是否下了商品订单
                        $orderGoodsItem = Db::name('qt_product_order_item')
                            ->where(['goods_id' => $duanweiData['product_id'], 'room_id' => $orderProject['room_id'], 'sale_id' => $getData['engineer_id']])
                            ->find();
                        if (!empty($orderGoodsItem)) {
                            \app\common\model\Duanwei::delDuanweiPrice($orderGoodsItem['id']);
                        }
                    }
                    Db::commit();
                } catch (Exception $exception) {
                    Db::rollback();
                    $this->result('操作失败' . $exception->getFile() . $exception->getLine() . $exception->getMessage(), '', 204);
                }
            } elseif ($this->storeInfo['receiver_order_commission_type'] == '3') {
                //删除订单提成
                Db::name('qt_commission_log')->where(['type' => '1', 'order_project_id' => $orderProject['id']])->delete();
            }
            //如果有手牌先减去老项目金额，再加新的金额
            if ($orderProject['hand_card_id'] != '') {
                $handGrant = Db::name('qt_hand_grant')
                    ->where(['hand_card_id' => $orderProject['hand_card_id'], 'status' => '2'])
                    ->order('id desc')
                    ->find();
                if (!empty($handGrant)) {
                    Db::name('qt_hand_grant')->where(['id' => $handGrant['id']])->setDec('money', $orderProject['price']);
                    Db::name('qt_hand_grant')->where(['id' => $handGrant['id']])->setInc('money', $newProject['price']);
                } else {
                    $this->result('手牌状态不正确，无法换项', '', 204);
                }
            }
            $this->result('操作成功', '', 200);
        } else {
            $this->result('非法请求', '', 204);
        }
    }


    /**
     * 获取当前房间等待项目(首页房间等待用)
     */
    public function waitList()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['limit'])) {
                $getData['limit'] = '10';
            }
            $map = [];
            //房间筛选
            if (!empty($getData['room_id'])) {
                $map[] = ['w.room_id', '=', $getData['room_id']];
            }
            //技师筛选
            if (!empty($getData['work_number'])) {
                $userId = Db::name('qt_users')->where(['store_id' => $this->userInfo['store_id'], 'work_number' => $getData['work_number']])->value('id');
                if (empty($userId)) {
                    $this->result('暂无此技师', [], 200);
                }
                $map[] = ['w.engineer_id', '=', $userId];
            }
            //等待时间筛选
            if (!empty($getData['wait_time'])) {
                $time = time() - ($getData['wait_time'] * 60);
                $map[] = ['w.create_time', '<', $time];
            }
            //项目筛选
            if (!empty($getData['project_id'])) {
                $map[] = ['w.project_id', '=', $getData['project_id']];
            }
            $data = Db::name('qt_wait')
                ->alias('w')
                ->leftJoin('qt_project p', 'p.id = w.project_id')
                ->leftJoin('qt_room r', 'r.id = w.room_id')
                ->leftJoin('qt_users u', 'u.id = w.engineer_id')
                ->field('w.id,w.project_id,p.name as project_name,r.name as room_name,u.work_number,w.sex,w.create_time,w.create_id,w.engineer_id,w.is_first')
                ->where($map)
                ->where(['w.status' => '1', 'w.delay_time' => '0'])
                ->order('w.id desc')
                ->paginate($getData['limit'])->each(function ($item) {
                    $item['create_name'] = Db::name('qt_users')->where('id', $item['create_id'])->value('real_name');
                    $item['end_time'] = Db::name('qt_order_queue')->where('user_id', $item['engineer_id'])->value('end_time');
                    return $item;
                });
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 优先当前技师
     */
    public function waitFirst()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['id'])) {
                $this->result('缺少参数', '', 204);
            }
            $update = Db::name('qt_wait')->where(['id' => $getData['id']])->update(['is_first' => $getData['is_first']]);
            if ($update !== false) {
                $this->result('更新成功', '', 200);
            }
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 优先当前技师
     */
    public function waitDelete()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['id'])) {
                $this->result('缺少参数', '', 204);
            }
            $wait = Db::name('qt_wait')->where('id', $getData['id'])->find();
            //判断技师数量更改房间状态
            $roomEngineer = Db::name('qt_order_queue')->where(['room_id' => $wait['room_id']])->count();
            if ($roomEngineer <= 1) {
                Db::name('qt_room')->where(['id' => $wait['room_id']])->update(['status_id' => '10']);
            }
            try {
                Db::startTrans();
                //删除等待列表
                Db::name('qt_wait')->where(['id' => $getData['id']])->delete();
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('删除失败', '', 204);
            }
            $this->result('删除成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 修改当前技师
     */
    public function waitSave()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['id'])) {
                $this->result('缺少参数', '', 204);
            }
            unset($getData['create_time']);
            $wait = Db::name('qt_wait')->where('id', $getData['id'])->update($getData);
            if ($wait !== false) {
                $this->result('更新成功', '', 200);
            }
        }
        $this->result('无效的请求', '', 204);
    }

}
